package site.jlopen.service.imp;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import site.jlopen.domain.node.KusciaNodeRoute;
import site.jlopen.domain.node.event.KusciaNodeEvent;
import site.jlopen.domain.node.event.KusciaNodeRouteEvent;
import site.jlopen.entity.BaseResponse;
import site.jlopen.entity.KusciaApiInfo;
import site.jlopen.entity.node.RouteSearchResult;
import site.jlopen.kuscia.model.route.NodeRouteVo;
import site.jlopen.kuscia.service.noderoute.KusciaNodeRouteManager;
import site.jlopen.mapper.node.KusciaNodeMapper;
import site.jlopen.mapper.node.KusciaNodeRouteMapper;
import site.jlopen.service.intf.node.NodeRouteService;
import site.jlopen.utils.id.IdUtils;

@Service
public class NodeRouteServiceImpl implements NodeRouteService {
	private static Logger logger = LoggerFactory.getLogger(NodeRouteServiceImpl.class);

	@Autowired
	private KusciaNodeMapper nodeMapper;
	@Autowired
	private KusciaNodeRouteMapper nodeRouteMapper;
	@Autowired
	private KusciaNodeRouteManager nodeRouteManager;

	@Override
	public BaseResponse<String> bind(Long userId, Long srcNodeId, Long dstNodeId, int bindType) {
		KusciaNodeRouteEvent routrInfo = nodeRouteMapper.selectByInfo(
				new KusciaNodeRoute().setRouteSrcNode(srcNodeId).setRouteDstNode(dstNodeId));
		if(null != routrInfo) {
			return new BaseResponse<String>().error("已存在绑定，请自行刷新状态");
		}
		String routeName = null;
		KusciaNodeEvent srcNode = nodeMapper.selectByKey(srcNodeId);
		KusciaNodeEvent dstNode = nodeMapper.selectByKey(dstNodeId);
		KusciaApiInfo apiInfo = new KusciaApiInfo(srcNode.getNodeProtocol(), srcNode.getNodeGrpc()).ext(srcNode.getNodeToken(), srcNode.getNodeCert(), srcNode.getNodeKey(), srcNode.getNodeCa());
		if(bindType == 1) {
			NodeRouteVo routeVo = nodeRouteManager.queryDomainRoute(apiInfo, srcNode.getNodeCode(), dstNode.getNodeCode());
			if(null != routeVo) {
				return new BaseResponse<String>().error("合作节点已存在于kuscia，请使用关系绑定");
			}
			routeName = nodeRouteManager.createDomainRoute(apiInfo, srcNode.getNodeCode(), dstNode.getNodeCode(), dstNode.getNodeNet());
		}
		if(bindType == 1 && StringUtils.isBlank(routeName)) {
			return new BaseResponse<String>().error("实时绑定失败");
		}
		routrInfo = new KusciaNodeRouteEvent();
		routrInfo.setRouteId(IdUtils.SnowFlakeId());
		routrInfo.setRouteSrcNode(srcNodeId);
		routrInfo.setRouteDstNode(dstNodeId);
		routrInfo.setRouteUserId(userId);
		routrInfo.setRouteDeleted(0);
		routrInfo.setRouteStatus(1);
		routrInfo.setRouteCreate(new Date());
		int row = nodeRouteMapper.insertSelective(routrInfo);
		if(row > 0) {
			
		}
		return new BaseResponse<String>().dbRes(row, "绑定成功");
	}

	@Override
	public List<KusciaNodeRouteEvent> list(Long userId) {
		Map<String, Object> records = new HashMap<String, Object>();
		records.put("routeUserId", userId);
		List<KusciaNodeRouteEvent> list = nodeRouteMapper.selectAllNotPage(records);
		for (KusciaNodeRouteEvent route : list) {
			KusciaNodeEvent srcNode = nodeMapper.selectByKey(route.getRouteSrcNode());
			KusciaNodeEvent dstNode = nodeMapper.selectByKey(route.getRouteDstNode());
			route.setSrcNode(srcNode);
			route.setDstNode(dstNode);
		}
		return list;
	}

	@Override
	public BaseResponse<String> unbind(Long routeId) {
		KusciaNodeRouteEvent routrInfo = nodeRouteMapper.selectByKey(routeId);
		KusciaNodeEvent srcNode = nodeMapper.selectByKey(routrInfo.getRouteSrcNode());
		KusciaNodeEvent dstNode = nodeMapper.selectByKey(routrInfo.getRouteDstNode());
		KusciaApiInfo apiInfo = new KusciaApiInfo(srcNode.getNodeProtocol(), srcNode.getNodeGrpc()).ext(srcNode.getNodeToken(), srcNode.getNodeCert(), srcNode.getNodeKey(), srcNode.getNodeCa());
		int row = nodeRouteMapper.deleteByKey(routeId);
		if(row > 0) {
			nodeRouteManager.deleteDomainRoute(apiInfo, srcNode.getNodeCode(), dstNode.getNodeCode());
		}
		return new BaseResponse<String>().dbRes(row, "解绑成功");
	}

	@Override
	public BaseResponse<String> restatus(Long routeId) {
		KusciaNodeRouteEvent routrInfo = nodeRouteMapper.selectByKey(routeId);
		KusciaNodeEvent srcNode = nodeMapper.selectByKey(routrInfo.getRouteSrcNode());
		KusciaNodeEvent dstNode = nodeMapper.selectByKey(routrInfo.getRouteDstNode());
		KusciaApiInfo apiInfo = new KusciaApiInfo(srcNode.getNodeProtocol(), srcNode.getNodeGrpc()).ext(srcNode.getNodeToken(), srcNode.getNodeCert(), srcNode.getNodeKey(), srcNode.getNodeCa());
		NodeRouteVo routeVo = nodeRouteManager.queryDomainRoute(apiInfo, srcNode.getNodeCode(), dstNode.getNodeCode());
		int status = 0;
		if(null == routeVo) {
			String routeName = nodeRouteManager.createDomainRoute(apiInfo, srcNode.getNodeCode(), dstNode.getNodeCode(), dstNode.getNodeNet());
			if(StringUtils.isBlank(routeName)) {
				status = 1;
			}
		} /*else if (routeVo.isSuccess() == false) {
			status = 1;
			}*/
		routrInfo.setRouteStatus(status);
		nodeRouteMapper.updateSelective(routrInfo);
		return new BaseResponse<String>().success("状态已刷新");
	}

	@Override
	public BaseResponse<String> delRoute(Long routeId) {
		int row = nodeRouteMapper.deleteByKey(routeId);
		return new BaseResponse<String>().dbRes(row, "清除成功");
	}

	@Override
	public BaseResponse<RouteSearchResult> search(Long srcNode, Long dstNode) {
		if(srcNode.compareTo(dstNode) == 0) {
			return new BaseResponse<RouteSearchResult>().error("不能绑定同一个节点");
		}
		KusciaNodeEvent destnode = nodeMapper.selectByKey(dstNode);
		if(null == destnode) {
			return new BaseResponse<RouteSearchResult>().error("搜索节点不存在");
		}
		KusciaNodeEvent srcnode = nodeMapper.selectByKey(srcNode);
		RouteSearchResult result = new RouteSearchResult();
		result.setDstNodeId(destnode.getNodeId());
		result.setDstNodeCode(destnode.getNodeCode());
		result.setDstNodeTitle(destnode.getNodeTitle());
		result.setDstNodeGateway(destnode.getNodeGateway());
		result.setSrcNodeCode(srcnode.getNodeCode());
		result.setSrcNodeGateway(srcnode.getNodeGateway());
		return new BaseResponse<RouteSearchResult>().success("搜索成功").setData(result);
	}

}
